<template>
  <div class="bottom_padding_1389">
    <div class="scale_subject">
      <div class="subject_item block_item" v-for="(r, i) in questionList" :key="i">
        <div class="subject_text" :class="{ bottom_line: i != 4 - 1 }">
          {{ r.question }}
        </div>
        <div class="subject_answer">
          <div class="answer_item" v-for="(sr, si) in r.options" :key="sr.id || si" @click="answerOperate(r, sr)">
            <img :src="r.select === sr.name ? inactiveIcon : activeIcon" alt="" class="select_img">
            <div class="answer_text">{{ sr.name }}</div>
          </div>
        </div>
      </div>
    </div>

    <button class="btn submit_btn" v-if="calcParamsType == 1" @click="submitAnswer()">
      提交
    </button>
  </div>
</template>

<script>
import http from "@/server/http";
import { formatDate } from "@/utils/time";
import { getTemplateList, submitSelfAssessment } from "@/api/funcation/selfAssessment";
export default {
  data() {
    return {
      activeIcon: require("@/assets/images/common/radio1.png"),
      inactiveIcon: require("@/assets/images/common/radio11.png"),
      questionList: [],
      config: {
        template_id: 1,
        type_id: 1,
      },
      selfRecordData: [],
    };
  },
  computed: {
    calcCheck() {
      return (r, sr) => {
        return r["select"] == sr.name;
      };
    },
    // 1新增 2编辑
    calcParamsType() {
      return this.$route.params.type || 1;
    },
    calcParamsId() {
      return this.$route.params.id;
    },
  },
  methods: {
    // 时间格式化
    formatDate,

    answerOperate(question, selectedOption) {
      question.select = selectedOption.name;
    },

    // 简化计算函数

    async getSelfAssessmentQuestion() {
      //固定传id为1
      let { data } = await getTemplateList({ id: 1 })
      // this.questionList = data[0].templates[0].children
      this.questionList = data[0].templates[0].children.map((i) => {
        return {
          id: i.id,
          question: i.name,
          select: "",
          options: i.templateOptions.map((j) => {
            return { name: j.name, id: j.id };
          }),
        };
      });
      // }
      // }
    },
    //提交答案
    async submitAnswer() {
      // let list = JSON.parse(JSON.stringify(this.questionList));
      // list.map(item => {
      //   const selectedOption = item.options.find(option => option.name === item.select);
      //   return {
      //     questionId: item.id,
      //     answersId: selectedOption ? selectedOption.id : null
      //   };
      // });
      // let rea = await submitSelfAssessment()
      let list = this.questionList.filter(i => i.select == '');
      if (list.length > 0) {
        return this.$toast.fail(`您还有${list.length}个问题未作答！`)
      }
      if (this.calcParamsType == 1 && this.calcParamsId != 0) {
        this.taskAnswer();
        this.selfAnswer(true);
      } else {
        this.selfAnswer();
      }
    },
    async taskAnswer() {
      let { data } = await http({
        url: "/psychological/scheduling/submit_self_evaluation",
        method: "POST",
        data: {
          self_task_id: this.calcParamsId,
          result: JSON.stringify(
            this.questionList.map((i) => {
              return { ...i, options: i.options.map((j) => j.name) };
            })
          ),
        },
      });
      if (data.code == 200) {
        this.$toast.success("提交成功！");
        this.$router.go(-1);
      }
    },
    async selfAnswer(flag) {
      // if (!this.questionList.every((item) => item.select))
      //   return this.$toast.fail("请选择完题目！");

      const answersResult = this.questionList.map(question => {

        // 找到当前问题中，select匹配的options项
        const matchedOption = question.options.find(
          option => option.name === question.select
        );
        // 返回格式：{questionId: 问题id, answersId: 匹配到的选项id}
        return {
          questionId: question.id,
          answersId: matchedOption ? matchedOption.id : '' // 若未匹配到则为null
        };
      });
      let par = {
        user_id: this.$store.state.INFO.id,
        type_id: 1,
        source: 1,
        message_id: 0,
        content: answersResult,
      }
      let res = await submitSelfAssessment(par)
      if (res.code == 200) {
        this.$toast.success("提交成功！");
        this.$router.go(-1);
      }
    },
    async getAnswer() {
      try {
        let { data } = await http({
          url: "/psychological/scheduling/get_self_task_record",
          method: "POST",
          data: {
            id: this.calcParamsId,
          },
        });
        if (data.code == 200) {
          let { create_time, result } = data.data;
          let list = JSON.parse(result);
          this.questionList = list.map((i) => {
            return {
              ...i,
              options: i.options.map((j) => {
                return { name: j };
              }),
            };
          });
          this.$emit("updateTime", this.formatDate(+create_time * 1000));
        }
      } catch (e) { }
    },
    async getUserRecord() {
      let uid = this.$store.state.INFO.id;
      try {
        let { data } = await http({
          url: "/user/archive/get",
          method: "POST",
          data: {
            uid,
          },
        });
        if (data.code == 200) {
          let { type_id, template_id } = this.config;
          this.selfRecordData = data.data.filter(
            (i) => i.type_id == type_id && i.template_id == template_id
          );
        }
      } catch (e) { }
    },
  },
  async mounted() {
    if (this.calcParamsType == 1) {
      await this.getSelfAssessmentQuestion();
      // this.getUserRecord();
    } else {
      this.getAnswer();
    }
  },
};
</script>

<style scoped>
.scale_subject {
  display: grid;
  gap: 10.42px;
}

.block_item {
  width: 100%;
  height: fit-content;
  background: #ffffff;
  border-radius: 6.94px;
  box-sizing: border-box;
}

.bottom_line {
  position: relative;
}

.bottom_line::before {
  display: block;
  width: 100%;
  height: 0.35px;
  background: #dddddd;
  position: absolute;
  bottom: 0;
  left: 0;
  content: "";
}

.subject_item {
  margin: 0 auto;
  padding: 10.76px 13.89px 15.67px 13.89px;
  box-sizing: border-box;
  font-family: Microsoft YaHei, Microsoft YaHei-Regular;
  font-weight: 400;
  color: #333333;
}

.answer_check {
  /* width: 14.58px;
  height: 14.58px;
  background: rgba(51, 51, 51, 0);
  border: 1.39px solid #888888;
  box-sizing: border-box;
  border-radius: 50%;
  margin-top: 5.21px; */
}

.subject_text {
  line-height: 26.39px;
  font-size: 15.97px;
  margin-bottom: 10.72px;
  padding-bottom: 11.46px;
  box-sizing: border-box;
  word-break: break-all;
  text-align: justify;
}

.subject_answer {
  display: grid;
  gap: 10.41px;
}

.answer_item {
  display: flex;
  align-items: center;
  line-height: 26.39px;
  font-size: 15.97px;
  display: grid;
  grid-template-columns: 14.93px auto;
  gap: 14.14px;
}



.is_check .answer_check::after {
  display: block;
  content: "";
  border-radius: 50%;
  box-sizing: border-box;
  width: 8.33px;
  height: 8.33px;
  background: linear-gradient(0deg, #ffffff 0%, rgba(255, 255, 255, 0) 10%),
    #0aa7f4;
}

.is_check {
  width: 14.58px;
  height: 14.58px;
  background: rgba(51, 51, 51, 0);
  border: 1.39px solid #888888;
  box-sizing: border-box;
  border-radius: 50%;
  margin-top: 5.21px;
  width: 14.58px;
  height: 14.58px;
  background: #00aeff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.answer_text {
  word-break: break-all;
  text-align: justify;
}

.is_check .answer_text {
  color: #00aeff;
  font-size: 14.58px;
}

.select_img {
  width: 14.58px;
  height: 14.58px;
}

.submit_btn {
  margin-top: 10.42px;
}

.btn {
  width: 347.22px;
  height: 48.61px;
  display: block;
  margin: 34.72px auto 20px;
}
</style>